/**
 * 
 */
package vin.echo.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;

import org.apache.log4j.Logger;

import vin.echo.core.annotation.Function;
import vin.echo.core.request.JSonable;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * 
 * request args ---> hashmap
 * request args ---> jsonable
 * request args ---> 自动切换
 * 
 * @author Vin
 * 
 */
public class EchoWrapper {
	private static final Logger LOG = Logger.getLogger(EchoWrapper.class);
	private EchoService service;

	public EchoWrapper(EchoService service) {
		this.service = service;
	}

	public void invoke(Method method, String args)
			throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {

		int argsCount = method.getParameterTypes().length;
		Function funcDesc = method.getAnnotation(Function.class);
		Gson gson = new GsonBuilder().create();

		switch (argsCount) {
		case 0:
			method.invoke(service);
			break;
		case 1:
			if (args != null&&funcDesc!=null) {
				if(funcDesc.requsetType().equals(HashMap.class)){
					Type exceptType = new TypeToken<HashMap<String,String>>(){}.getType();
					
					@SuppressWarnings("unchecked")
					HashMap<String,String> webRequset = (HashMap<String,String>) gson.fromJson(args,exceptType);
					method.invoke(service, webRequset);
				}else{
					JSonable webRequset = (JSonable) gson.fromJson(args,
							funcDesc.requsetType());
					method.invoke(service, webRequset);
				}
			}else if(args != null){
				//TODO
			}
			break;
		default:
			LOG.warn("no method is invoked. ");
			break;
		}
		
	}
	/**
	 * 动态切换参数
	 */
	private void distMapping(){
		
	}
}
